package com.car.rental.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.car.rental.common.core.exception.BusinessException;
import com.car.rental.common.core.response.ResponseResult;
import com.car.rental.order.dto.OrderCreateDTO;
import com.car.rental.order.entity.RentalOrder;
import com.car.rental.order.enums.OrderStatus;
import com.car.rental.order.mapper.OrderMapper;
import com.car.rental.order.service.MessageService;
import com.car.rental.order.service.OrderService;
import com.car.rental.order.vo.OrderDetailVO;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.amqp.rabbit.core.RabbitTemplate;

import java.util.UUID;
import java.util.HashMap;
import java.util.Map;

@Service
@RequiredArgsConstructor
public class OrderServiceImpl extends ServiceImpl<OrderMapper, RentalOrder> implements OrderService {

    private final MessageService messageService;
    private final RabbitTemplate rabbitTemplate;
    private static final int VEHICLE_STATUS_MAINTENANCE = 0;  // 维修中状态码

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<String> createOrder(Long userId, OrderCreateDTO createDTO) {
        // 1. 参数校验
        if (createDTO.getEndTime().isBefore(createDTO.getStartTime())) {
            throw new BusinessException("结束时间不能早于开始时间");
        }
        
        // 2. 生成订单编号
        String orderNo = UUID.randomUUID().toString().replace("-", "");
        
        // 3. 创建订单
        RentalOrder order = new RentalOrder();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setVehicleId(createDTO.getVehicleId());
        order.setStartTime(createDTO.getStartTime());
        order.setEndTime(createDTO.getEndTime());
        order.setTotalAmount(createDTO.getAmount());  // 使用 totalAmount
        order.setStatus(OrderStatus.PENDING_PAYMENT.getCode());
        
        save(order);
        
        // 发送订单创建消息
        messageService.sendOrderStatusMessage(orderNo);
        
        return ResponseResult.success(orderNo);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Void> cancelOrder(Long userId, String orderNo) {
        RentalOrder order = getByOrderNo(userId, orderNo);
        
        if (order.getStatus() != OrderStatus.PENDING_PAYMENT.getCode() 
            && order.getStatus() != OrderStatus.PAID.getCode()) {
            throw new BusinessException("当前订单状态不允许取消");
        }
        
        order.setStatus(OrderStatus.CANCELLED.getCode());
        updateById(order);
        
        // 发送订单取消消息
        messageService.sendOrderStatusMessage(orderNo);
        
        return ResponseResult.success();
    }

    @Override
    public ResponseResult<OrderDetailVO> getOrderDetail(Long userId, String orderNo) {
        RentalOrder order = getByOrderNo(userId, orderNo);
        OrderDetailVO detailVO = convertToDetailVO(order);
        return ResponseResult.success(detailVO);
    }

    @Override
    public ResponseResult<Page<OrderDetailVO>> getUserOrders(Long userId, Integer status, Integer current, Integer size) {
        // 创建分页对象
        Page<RentalOrder> page = new Page<>(current, size);
        
        // 构建查询条件
        LambdaQueryWrapper<RentalOrder> wrapper = new LambdaQueryWrapper<RentalOrder>()
                .eq(RentalOrder::getUserId, userId)
                .eq(status != null, RentalOrder::getStatus, status)
                .orderByDesc(RentalOrder::getCreateTime);
        
        // 先查询总数
        Long total = baseMapper.selectCount(wrapper);
        
        // 执行分页查询
        page = baseMapper.selectPage(page, wrapper);
        
        // 转换结果
        Page<OrderDetailVO> resultPage = new Page<>(current, size);
        resultPage.setTotal(total);  // 设置实际的总数
        resultPage.setRecords(page.getRecords().stream()
                .map(this::convertToDetailVO)
                .toList());
        
        return ResponseResult.success(resultPage);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Void> completeOrder(Long userId, String orderNo) {
        RentalOrder order = getByOrderNo(userId, orderNo);
        
        if (order.getStatus() != OrderStatus.IN_USE.getCode()) {
            throw new BusinessException("当前订单状态不允许完成");
        }
        
        order.setStatus(OrderStatus.COMPLETED.getCode());
        updateById(order);
        
        // 发送订单完成消息
        messageService.sendOrderStatusMessage(orderNo);
        
        return ResponseResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Void> pickupVehicle(Long userId, String orderNo) {
        // 1. 查询订单
        RentalOrder order = getByOrderNo(userId, orderNo);
        
        // 2. 检查订单状态
        if (order.getStatus() != OrderStatus.PAID.getCode()) {
            throw new BusinessException("当前订单状态不允许取车");
        }
        
        // 3. 更新订单状态为租用中
        order.setStatus(OrderStatus.IN_USE.getCode());
        updateById(order);
        
        // 4. 发送订单状态变更消息
        messageService.sendOrderStatusMessage(orderNo);
        
        return ResponseResult.success();
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResponseResult<Void> returnVehicle(Long userId, String orderNo) {
        // 1. 查询订单
        RentalOrder order = getByOrderNo(userId, orderNo);
        
        // 2. 检查订单状态
        if (order.getStatus() != OrderStatus.IN_USE.getCode()) {
            throw new BusinessException("当前订单状态不允许还车");
        }
        
        // 3. 更新订单状态为已完成
        order.setStatus(OrderStatus.COMPLETED.getCode());
        updateById(order);
        
        // 4. 发送消息更新车辆状态为维修中 (0 表示维修中)
        Map<String, Object> message = new HashMap<>();
        message.put("vehicleId", order.getVehicleId());
        message.put("status", VEHICLE_STATUS_MAINTENANCE);  // 使用常量
        
        rabbitTemplate.convertAndSend(
            "vehicle.status.exchange",
            "vehicle.status",
            message
        );
        
        return ResponseResult.success();
    }

    @Override
    public ResponseResult<OrderDetailVO> getOrderDetailNoAuth(String orderNo) {
        RentalOrder order = getOne(new LambdaQueryWrapper<RentalOrder>()
                .eq(RentalOrder::getOrderNo, orderNo));
                
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        OrderDetailVO detailVO = convertToDetailVO(order);
        return ResponseResult.success(detailVO);
    }

    public RentalOrder getByOrderNo(Long userId, String orderNo) {
        RentalOrder order = getOne(new LambdaQueryWrapper<RentalOrder>()
                .eq(RentalOrder::getOrderNo, orderNo)
                .eq(RentalOrder::getUserId, userId));
                
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        return order;
    }

    private OrderDetailVO convertToDetailVO(RentalOrder order) {
        OrderDetailVO detailVO = new OrderDetailVO();
        BeanUtils.copyProperties(order, detailVO);
        detailVO.setStatusDesc(OrderStatus.getByCode(order.getStatus()).getDescription());
        return detailVO;
    }
} 